from flask import Flask, request, jsonify
from flask_cors import CORS  # 允许前端跨域访问
from investment_history import InvestmentHistoryDB
from cash_flow import CashFlowDB
import json
import uuid
import time

app = Flask(__name__)
CORS(app)

# 设置密钥（用于未来的session或token加密）
app.config['SECRET_KEY'] = 'your-secret-key-here'

# 初始化数据库操作类
db = InvestmentHistoryDB()
cash_flow_db = CashFlowDB()

# 简单的用户存储（实际项目中应使用数据库）
users = {
    'admin': {
        'password': '11111',  # 实际项目中应使用加密存储
        'id': 1,
        'username': 'admin',
        'role': 'admin'
    },
    'chenyc': {
        'password': '11111',  # 实际项目中应使用加密存储
        'id': 2,
        'username': 'chenyc',
        'role': 'user'
    }
}

# 存储活跃的token
active_tokens = {}

# 生成token的函数
def generate_token(user_id):
    token = str(uuid.uuid4())
    # 存储token信息，包括用户ID和创建时间
    active_tokens[token] = {
        'user_id': user_id,
        'created_at': time.time()
    }
    return token

# 验证token的函数
def verify_token(token):
    if token not in active_tokens:
        return None
    
    token_info = active_tokens[token]
    # 检查token是否过期（这里设置24小时过期）
    if time.time() - token_info['created_at'] > 24 * 3600:
        # token过期，删除它
        del active_tokens[token]
        return None
    
    user_id = token_info['user_id']
    # 查找用户信息
    for username, user_info in users.items():
        if user_info['id'] == user_id:
            return user_info
    
    return None

# API保护装饰器
def token_required(f):
    def decorator(*args, **kwargs):
        token = request.headers.get('Authorization')
        
        # 如果没有提供token，检查url参数中是否有token
        if not token:
            token = request.args.get('token')
        
        # 如果还是没有token，返回未授权
        if not token:
            return jsonify({'error': '未提供认证token'}), 401
        
        # 验证token
        user = verify_token(token)
        if not user:
            return jsonify({'error': '无效或过期的token'}), 401
        
        # 将用户信息添加到请求对象中，以便在路由函数中使用
        request.user = user
        return f(*args, **kwargs)
    
    decorator.__name__ = f.__name__
    return decorator

@app.route('/api/test')
def test():
    return jsonify({"msg": "Hello from Flask"})

# 登录API
@app.route('/api/login', methods=['POST'])
def login():
    try:
        data = request.json
        username = data.get('username')
        password = data.get('password')
        
        # 检查必填字段
        if not all([username, password]):
            return jsonify({"error": "用户名和密码不能为空"}), 400
        
        # 检查用户是否存在
        if username not in users:
            return jsonify({"error": "用户名或密码错误"}), 401
        
        # 检查密码是否正确
        user = users[username]
        if user['password'] != password:
            return jsonify({"error": "用户名或密码错误"}), 401
        
        # 生成token
        token = generate_token(user['id'])
        
        return jsonify({
            "success": True,
            "token": token,
            "userInfo": {
                "id": user['id'],
                "username": user['username'],
                "role": user['role']
            },
            "message": "登录成功"
        }), 200
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 新增投资记录
@app.route('/api/investment-history', methods=['POST'])
@token_required
def add_investment_record():
    try:
        data = request.json
        date = data.get('date')
        cny = data.get('cny')
        # 获取投资类别，如果没有提供则使用默认值
        category = data.get('category', '货币基金')
        
        # 获取定存相关字段（如果有）
        deposit_start_date = data.get('deposit_start_date')
        deposit_duration = data.get('deposit_duration')
        deposit_rate = data.get('deposit_rate')
        
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 验证必填字段
        if not all([date, cny is not None]):
            return jsonify({"error": "缺少必填字段"}), 400
        
        # 新增记录，包含用户ID和类别，以及定存相关字段
        record_id = db.add_record(
            user_id=user_id,
            date=date,
            cny=float(cny),
            category=category,
            deposit_start_date=deposit_start_date,
            deposit_duration=deposit_duration,
            deposit_rate=deposit_rate
        )
        
        return jsonify({
            "success": True,
            "record_id": record_id,
            "message": "新增记录成功"
        }), 201
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 获取所有投资记录
@app.route('/api/investment-history', methods=['GET'])
@token_required
def get_all_investment_records():
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 根据用户ID获取记录
        records = db.get_all_records(user_id)
        return jsonify({
            "success": True,
            "data": records
        }), 200
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 获取单条投资记录
@app.route('/api/investment-history/<int:record_id>', methods=['GET'])
@token_required
def get_investment_record(record_id):
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 根据用户ID和记录ID获取记录
        record = db.get_record(record_id, user_id)
        if not record:
            return jsonify({"error": "记录不存在或不属于当前用户"}), 404
        
        return jsonify({
            "success": True,
            "data": record
        }), 200
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 修改投资记录
@app.route('/api/investment-history/<int:record_id>', methods=['PUT'])
@token_required
def update_investment_record(record_id):
    try:
        data = request.json
        
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 检查记录是否存在且属于当前用户
        if not db.get_record(record_id, user_id):
            return jsonify({"error": "记录不存在或不属于当前用户"}), 404
        
        # 准备更新数据
        update_data = {}
        if 'date' in data:
            update_data['date'] = data['date']
        if 'cny' in data:
            update_data['cny'] = float(data['cny'])
        if 'usd' in data:
            update_data['usd'] = float(data['usd'])
        if 'exchange_rate' in data:
            update_data['exchange_rate'] = float(data['exchange_rate'])
        if 'category' in data:
            update_data['category'] = data['category']
        # 添加定存相关字段
        if 'deposit_start_date' in data:
            update_data['deposit_start_date'] = data['deposit_start_date']
        if 'deposit_duration' in data:
            update_data['deposit_duration'] = data['deposit_duration']
        if 'deposit_rate' in data:
            update_data['deposit_rate'] = data['deposit_rate']
        
        # 如果没有要更新的字段
        if not update_data:
            return jsonify({"error": "没有要更新的字段"}), 400
        
        # 更新记录，包含用户ID
        success = db.update_record(record_id, user_id, **update_data)
        
        if success:
            return jsonify({
                "success": True,
                "message": "修改记录成功"
            }), 200
        else:
            return jsonify({"error": "修改记录失败"}), 500
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 删除投资记录
@app.route('/api/investment-history/<int:record_id>', methods=['DELETE'])
@token_required
def delete_investment_record(record_id):
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 检查记录是否存在且属于当前用户
        if not db.get_record(record_id, user_id):
            return jsonify({"error": "记录不存在或不属于当前用户"}), 404
        
        # 删除记录，包含用户ID
        success = db.delete_record(record_id, user_id)
        
        if success:
            return jsonify({
                "success": True,
                "message": "删除记录成功"
            }), 200
        else:
            return jsonify({"error": "删除记录失败"}), 500
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 获取指定日期范围内的记录
@app.route('/api/investment-history/range', methods=['GET'])
@token_required
def get_investment_records_by_range():
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        if not all([start_date, end_date]):
            return jsonify({"error": "缺少日期范围参数"}), 400
        
        # 根据用户ID和日期范围获取记录
        records = db.get_records_by_date_range(user_id, start_date, end_date)
        
        return jsonify({
            "success": True,
            "data": records
        }), 200
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 新增现金流水记录
@app.route('/api/cash-flow', methods=['POST'])
@token_required
def add_cash_flow_record():
    try:
        data = request.json
        asset_id = data.get('asset_id')
        flow_type = data.get('flow_type')
        amount = data.get('amount')
        channel = data.get('channel')
        fee = data.get('fee', 0)
        note = data.get('note')
        
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 验证必填字段
        if not all([flow_type, amount is not None, channel]):
            return jsonify({"error": "缺少必填字段"}), 400
        
        # 验证flow_type值
        valid_flow_types = ['deposit', 'withdraw', 'fiat_in', 'fiat_out']
        if flow_type not in valid_flow_types:
            return jsonify({"error": f"无效的flow_type，必须是以下值之一: {valid_flow_types}"}), 400
        
        # 新增记录
        record_id = cash_flow_db.add_record(
            user_id=user_id,
            asset_id=asset_id,
            flow_type=flow_type,
            amount=float(amount),
            channel=channel,
            fee=float(fee) if fee is not None else 0,
            note=note
        )
        
        return jsonify({
            "success": True,
            "flow_id": record_id,
            "message": "新增现金流水记录成功"
        }), 201
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 获取用户的所有现金流水记录
@app.route('/api/cash-flow', methods=['GET'])
@token_required
def get_cash_flow_records():
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 获取记录
        records = cash_flow_db.get_records_by_user(user_id)
        return jsonify({
            "success": True,
            "data": records
        }), 200
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

# 获取单条现金流水记录
@app.route('/api/cash-flow/<int:flow_id>', methods=['GET'])
@token_required
def get_cash_flow_record(flow_id):
    try:
        # 获取当前登录用户的ID
        user_id = request.user['id']
        
        # 根据用户ID和记录ID获取记录
        record = cash_flow_db.get_record_by_id(flow_id, user_id)
        if not record:
            return jsonify({"error": "记录不存在或不属于当前用户"}), 404
        
        return jsonify({
            "success": True,
            "data": record
        }), 200
    except Exception as e:
        return jsonify({"error": f"服务器内部错误: {str(e)}"}), 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)
